<template>
    <div id="container">
        <my-header></my-header>
        <el-main id="main">
            <!-- 搜索框 -->
            <div id="search-box">
                <el-input placeholder="请输入检索条件" v-model="search_input" class="input-with-select">
                    <el-select v-model="select" slot="prepend" placeholder="请选择" id="select">
                        <el-option label="关键字" value="1"></el-option>
                        <el-option label="课程" value="2"></el-option>
                        <el-option label="软件工程阶段" value="3"></el-option>
                        <el-option label="分类" value="4"></el-option>
                        <el-option label="标签" value="5"></el-option>
                        <el-option label="项目" value="6"></el-option>
                    </el-select>
                    <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
                </el-input>
            </div>
            <!-- 排序选项 -->
            <div id="order" v-if="resultType === 'normal'">
                排序选项：
                <el-radio v-model="radio" label="score" @change="handleOrderChange">评分</el-radio>
                <el-radio v-model="radio" label="download_count" @change="handleOrderChange">下载次数</el-radio>
            </div>
            <!-- 普通结果列表 -->
            <div v-if="resultType === 'normal'">
                <result-item v-for="item in resultList" :key="item.id" :item="item"></result-item>
            </div>
            <!-- 项目结果列表 -->
            <div v-if="resultType === 'project'">
                <project-item v-for="item in projectList" :key="item.id" :item="item"></project-item>
            </div>
            <div v-if="resultType === ''" id="not-found">
                <div id="not-found-image"></div>
                <br/>
                没有找到您需要的资源哦，请更换检索条件后重试~
            </div>
        </el-main>
        <my-footer></my-footer>
    </div>
</template>

<script>
import MyFooter from '../../components/MyFooter.vue';
import MyHeader from '../../components/MyHeader.vue'
import ResultItem from './components/ResultItem'
import ProjectItem from './components/ProjectItem'
import axios from 'axios'
export default {
    name:'Search',
    data:function(){
        return{
            search_input:'',
            select: '',
            radio:'score',
            resultType:'',
            resultList:[],
            projectList:[] 
        }
    },
    computed:{
        
    },
    created:function(){
        // 首页传来的搜索数据重新渲染到搜索页面
        this.search_input = this.$route.query.query;
        this.select = this.$route.query.type;

        // 判断搜索类型
        if(this.$route.query.type === '6'){
            this.resultType = 'project';
        }else{
            this.resultType = 'normal';
        }
        this.getSearchResult()        
        // 将数据以默认排序规则（评分）进行排序后渲染
        this.handleOrderChange('score');

    },
    methods:{
        handleOrderChange:function(value){
            //console.log(value);
            if(value === 'score'){
                this.orderByScore();
            }else{
                this.orderByDownloadCount();
            }
        },
        orderByScore:function(){
            this.resultList.sort(function(x,y){
                return y.score - x.score;
            });
        },
        orderByDownloadCount:function(){
            this.resultList.sort(function(x,y){
                return y.download_count - x.download_count;
            })
        },
        handleSearch(){
            if(this.search_input == ""){
                this.$message.error("请输入检索关键词");
                return;
            }
            // 先把数据清空
            this.resultList = [];
            this.projectList = [];
            this.resultType = '';
            // 再跳转
            this.$router.push({ path: 'search' ,query:{'query':this.search_input,'type':this.select}});
            this.getSearchResult();
        },
        getSearchResult:async function(){
            if(this.search_input == ""){
                this.$message.error("请输入检索关键词");
                return;
            }
            let post_data = {
                search_input:this.search_input,
                select:this.select
            }
            const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
              const res = await axios.post('/api/search/get_search_result',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("检索失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                    if(res.data.res.resultType === "normal" ){
                        this.resultList = [];
                        this.resultType = "normal";
                        //  此处处理数据
                        let result = [];
                        for(let i in res.data.res.resultList){
                          let temp = {
                              'id':res.data.res.resultList[i].file_id,
                              'type':res.data.res.resultList[i].type,
                              'name':res.data.res.resultList[i].name,
                              'location':[
                                  '实践项目资产子库',
                                  '实践项目过程资源集',
                                  '标准过程子集'
                              ],
                              'stage':res.data.res.resultList[i].stage,
                              'tags':res.data.res.resultList[i].tags.split(' '),
                              'course':res.data.res.resultList[i].course,
                              'score':res.data.res.resultList[i].score,
                              'download_count':res.data.res.resultList[i].download_count
                          };
                          result.push(temp);
                        }
                        this.resultList = result;
                    }else{
                        this.projectList = [];
                        this.resultType = "project";
                        //  此处处理数据
                        let result = [];
                        for(let i in res.data.res.resultList){
                          let temp = {
                              'id':res.data.res.resultList[i].pid,
                              'name':res.data.res.resultList[i].name,
                              'desc':res.data.res.resultList[i].desc,
                              'tags':res.data.res.resultList[i].tags.split(' '),
                              'course':res.data.res.resultList[i].course,
                              'owner':res.data.res.resultList[i].username,
                              'time':res.data.res.resultList[i].start_time.slice(0,10)+"到"+res.data.res.resultList[i].end_time.slice(0,10),
                              'isFinished':res.data.res.resultList[i].isFinished,
                              'enterpriseProject':res.data.res.resultList[i].enterprise_tag
                          };
                          result.push(temp);
                        }
                        this.projectList = result;
                    }
                    this.$notify({
                        title: '检索成功',
                        message: res.data.res.msg,
                        type: 'success'
                    });
                }else{
                    this.resultType = '';
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        }
    },
    components:{
        MyHeader,
        MyFooter,
        ResultItem,
        ProjectItem
    }
}
</script>

<style lang="scss" scoped>
#container{
    width: 100%;
    background-color: #eee;
    min-width: 950px;
    height: 100%;
    #main{
        width:70%;
        min-height: 700px;
        margin-left: 15%;
        margin-right: 15%;
        margin-top:30px;
        margin-bottom:30px;
        background-color: #fff;
        box-sizing: border-box;
        padding:50px;
        #search-box{
            width:60%;
            margin:0 auto;
            margin-bottom:20px;
        }
        #order{
            padding-left:50px;
            padding-top:10px;
            padding-bottom: 10px;
        }
        #not-found{
            text-align: center;
            width:100%;
            height:120px;
            margin-top:80px;
            #not-found-image{
                width:100px;
                height:100px;
                display: inline-block;
                background-image: url("~@/assets/pics/404.png");
                background-size:100px 100px;
                background-repeat:no-repeat;
                background-position:top center;
                background-color: transparent;
            }
        }
    }
}
.el-select{
    width:130px;
    text-align: center;
    height: 50px;
}
.input-with-select >>> .el-input__inner{
    height: 50px;
    line-height: 50px;
}
</style>